package cn.zhangfusheng.elasticsearch.template;

import cn.zhangfusheng.elasticsearch.dynamic.DyanmicExecuteResult;
import cn.zhangfusheng.elasticsearch.dynamic.DynamicAnalysis;
import cn.zhangfusheng.elasticsearch.dynamic.SqlAnalysisDetail;
import cn.zhangfusheng.elasticsearch.exception.GlobalSystemException;
import cn.zhangfusheng.elasticsearch.repository.ElasticSearchRepository;
import cn.zhangfusheng.elasticsearch.scan.ElasticSearchEntityRepositoryDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 动态字符串解析处理
 * @author fusheng.zhang
 * @date 2022-04-18 14:43:59
 */
public interface TemplateDynamicSqlApi extends Template, TemplateDynamicStrApi {

    Logger log = LoggerFactory.getLogger(TemplateDynamicSqlApi.class);

    default Object runWithSql(
            ElasticSearchEntityRepositoryDetail entityRepositoryDetail, Method method, Object[] args, String routing, String index) {
        try {
            Class<? extends ElasticSearchRepository<?>> daoClass = entityRepositoryDetail.getElasticSearchRepositoryClass();
            SqlAnalysisDetail sqlAnalysisDetail = new DynamicAnalysis().analysisWithSql(daoClass, method);
            DyanmicExecuteResult execute = sqlAnalysisDetail.execute(args);
            return this.runDynamicSql(entityRepositoryDetail, method, args, routing, index, execute);
        } catch (IOException e) {
            throw new GlobalSystemException(e);
        }
    }

}
